package org.fastsyncer.rest.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.fastsyncer.common.constant.CommonConstant;
import org.fastsyncer.common.util.CryptoUtils;
import org.fastsyncer.common.util.ApplicationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 存储登录用户的cookie信息
 * 
 * @ClassName: TicketCookie
 * @Description: 存储登录用户的cookie信息
 * @author: YangPei
 * @date: 2017年9月5日 上午11:15:27
 */
public class Ticket {

	private static final Logger logger = LoggerFactory.getLogger(Ticket.class);

	// 存放认证票据
//	private static CacheMap<Object, Object> map = CacheMap.getInstance();
	
//	/**
//	 * 获取票据对应的登录SessionId
//	 * 
//	 * @Title: get
//	 * @Description: 获取票据对应的登录SessionId
//	 * @param key
//	 *            票据
//	 * @return: String SessionId
//	 */
//	public static String get(String key) {
//		return (String) map.get(key);
//	}

//	/**
//	 * 存放票据对应的登录SessionId
//	 * 
//	 * @Title: get
//	 * @Description: 存放票据对应的登录SessionId
//	 * @param key
//	 *            票据
//	 * @param value
//	 *            SessionId
//	 * @return: boolean
//	 */
//	public static boolean put(String key, String value) {
//		try {
//			Long time = Long.parseLong(ApplicationUtil.getKey(CommonConstant.CONFIG_INTERCEPTOR_SESSION_MAX_AGE) + "000");
//			map.put(key, value, time);
//		} catch (NumberFormatException e) {
//			map.put(key, value);
//		}
//		return true;
//	}

//	/**
//	 * 移除票据对应的登录SessionId
//	 * 
//	 * @Title: get
//	 * @Description: 移除票据对应的登录SessionId
//	 * @param key
//	 *            票据
//	 * @return: boolean
//	 */
//	public static boolean remove(String key) {
//		return map.delete(key);
//	}

	/**
	 * 获取票据标识 ticket
	 * 
	 * @Title: getTicket
	 * @Description: 获取写入浏览器的cookie票据标识
	 * @return: String cookie票据标识
	 */
	public static String getTicket() {
		return ApplicationUtil.getKey(CommonConstant.CONFIG_INTERCEPTOR_TICKET);
	}

	/**
	 * 获取Cookie值
	 * 
	 * @Title: getCookie
	 * @Description: 获取Cookie值
	 * @param request
	 * @param key
	 *            Cookie名称
	 * @return: String Cookie值
	 */
	public static String getCookie(HttpServletRequest request, String key) {
		// 获取Cookie
		String value = "";
		Cookie[] diskCookies = request.getCookies();
		if (diskCookies != null) {
			int length = diskCookies.length;
			for (int i = 0; i < length; i++) {
				if (diskCookies[i].getName().equals(key)) {
					value = diskCookies[i].getValue();
					break;
				}
			}
		}
		return value;
	}
	
	/**
     * 获取Cookie值
     * 
     * @Title: hasTicket
     * @Description: 获取Cookie值
     * @param request
     * @param key
     *            Cookie名称
     * @return: String Cookie值
     */
    public static boolean hasTicket(HttpServletRequest request, String key) {
        boolean exits = false;
        Cookie[] diskCookies = request.getCookies();
        if (diskCookies != null) {
            int length = diskCookies.length;
            for (int i = 0; i < length; i++) {
                if (diskCookies[i].getName().equals(key)) {
                    exits = true;
                    break;
                }
            }
        }
        return exits;
    }

	/**
	 * 生成认证票据
	 * 
	 * @Title: createTicket
	 * @Description: 生成认证票据,如果验证失败，抛出异常
	 * @param request
	 * @param response
	 * @param username
	 *            帐号
	 * @param userpwd
	 *            密码
	 * @throws IllegalAccessError
	 * @return: void
	 * @throws Exception 
	 */
	public static void createTicket(HttpServletRequest request, HttpServletResponse response, String username,
			String userpwd) throws Exception {
		// 如果认证失败，直接返回null
		String acc = ApplicationUtil.getKey(CommonConstant.CONFIG_ADMIN_ACCOUNT);
		String pwd = ApplicationUtil.getKey(CommonConstant.CONFIG_ADMIN_PWD);
		// 解密
		userpwd = CryptoUtils.encodeBASE64(userpwd);
		boolean result = acc.equals(username) && pwd.equals(userpwd);
		if (!result) {
			throw new IllegalArgumentException("Account or password error.");
		}

        HttpSession session = request.getSession();
        session.setAttribute(Ticket.getTicket(), username);
        // 会话失效时间（秒）,默认五分钟
        Integer maxAge = 300;
        try {
            maxAge = Integer.parseInt(ApplicationUtil.getKey(CommonConstant.CONFIG_INTERCEPTOR_SESSION_MAX_AGE));
        } catch (NumberFormatException e) {
        }
        session.setMaxInactiveInterval(maxAge);
		logger.info("Get the ticket successfully.");
	}

}
